// pages/publish-product/publish-product.js
import { Article } from "../../models/article";
import { Upload } from "../../models/upload";
import { config } from "../../config/config";
import { UserInfo } from "../../models/userinfo";
import { Category } from "../../models/category";
import Toast from "../../miniprogram_npm/@vant/weapp/toast/toast";

Page({
  /**
   * 页面的初始数据
   */
  data: {
    id: "",
    fileList: [],
    radioValue: "1",
    isShow: false,

    title: "",
    content: "",
    checked: false,
    id: "",
    specAndPrice: [
      {
        spec: "",
        price: "",
        size: ""
      }
    ],
    btnDisable: "",
    userInfo: null,
    show: false,
    list1: [],
    list2: [],
    clist2: [],
    columns: [],
    selectIndex: [],
    config
  },

  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(options) {
    let data = new UserInfo();
    // this.data.userInfo = data.getUserInfo();
    this.setData({
      userInfo: data.getUserInfo()
    });
    await this.getList();

    if (options.id) {
      this.data.id = options.id;
      this.getTheData(options.id);
    }
  },
  titleChange(e) {
    this.data.title = e.detail;
  },
  contentChange(e) {
    this.data.content = e.detail;
  },
  arrayToString() {
    if (this.data.specAndPrice.length == 0) {
      return "";
    } else {
      let str = "";
      this.data.specAndPrice.forEach((item, index) => {
        let str1 = item.spec + ":" + item.price + ":" + item.size;
        if (index == 0) {
          str = str + str1;
        } else {
          str = str + "|" + str1;
        }
      });
      return str;
    }
  },
  handlePriceaAndMc(str) {
    return str.split("|").map(item => {
      let arr = item.split(":");
      return {
        spec: arr[0],
        price: arr[1],
        size: arr[2]
      };
    });
  },
  delItem(e) {
    console.log(e);
    if (this.data.specAndPrice.length == 1) {
      return Toast("至少保留一项");
    }
    let specAndPrice = this.data.specAndPrice.splice(
      e.currentTarget.dataset.index,
      1
    );
    this.setData({
      specAndPrice
    });
  },
  addMore() {
    this.data.specAndPrice.push({
      spec: "",
      price: "",
      size: ""
    });
    let specAndPrice = this.data.specAndPrice;

    this.setData({
      specAndPrice: specAndPrice
    });
  },
  async getTheData(id) {
    const data = await Article.GetTheData({ Id: id });
    let data2 = data.Data;
    let fileList = [];
    if (data2 && data2.Imags) {
      const Imags = data2.Imags.split(",");
      if (Imags.length > 0) {
        Imags.forEach(item => {
          fileList.push({
            url: item
          });
        });
      }
    }
    let specAndPrice = this.handlePriceaAndMc(data2.PriceaAndMc);
    console.log(specAndPrice);
    let name1 = this.findC1NameById(data2.Articlelassify_id);
    let name2 = this.findC2NameById(data2.Subclassfyid);
    console.log(data2)
    this.setData({
      fileList,
      title: data2.Title,
      content: data2.Content,
      checked: data2.Articlelassify_id == 1 ? false : true,
      specAndPrice,
      Articlelassify_id: data2.Articlelassify_id,
      Subclassfyid: data2.Subclassfyid,
      typeName: `${name1}/${name2}`
    });
  },
  findC1NameById(id) {
    let name = "";
    let item = this.data.list1.find(item => {
      return item.Id == id;
    });
    if (item && item.Name) {
      name = item.Name;
    }
    return name;
  },
  findC2NameById(id) {
    let name = "";
    let item = this.data.list2.find(item => {
      return item.Id == id;
    });
    if (item && item.Name) {
      name = item.Name;
    }
    return name;
  },
  afterRead(e) {
    let that = this;
    let file = e.detail.file;

    wx.uploadFile({
      url: `${config.apiBaseUrl}Base_Manage/Upload/UploadFileByForm`, // 仅为示例，非真实的接口地址
      filePath: file.url,
      name: "file",
      // formData: { user: 'test' },
      success(res) {
        // 上传完成需要更新 fileList
        console.log(res.data);
        let data = JSON.parse(res.data);
        console.log(data.url);
        const { fileList = [] } = that.data;
        fileList.push({ ...file, url: data.url });
        that.setData({ fileList });
      }
    });
  },
  delImg(e) {
    let index = e.detail.index;
    this.data.fileList.splice(index, 1);
    this.setData({
      fileList: this.data.fileList
    });
  },
  onChangeSwitch(e) {
    console.log("onChange");
    console.log(e);
    // 需要手动对 checked 状态进行更新
    this.setData({ checked: e.detail });
  },
  onChangeSwitchShow(e) {
    // 需要手动对 checked 状态进行更新
    this.setData({ isShow: e.detail });
  },
  priceChange(e) {
    console.log(e.currentTarget.dataset.index);
    console.log(e.detail);
    let index = e.currentTarget.dataset.index;
    this.data.specAndPrice[index].price = e.detail;
    let specAndPrice = this.data.specAndPrice;
    this.setData({
      specAndPrice
    });
  },
  sizeChange(e) {
    console.log(e);
    let index = e.currentTarget.dataset.index;
    this.data.specAndPrice[index].size = e.detail;
    let specAndPrice = this.data.specAndPrice;
    this.setData({
      specAndPrice
    });
  },
  nameChange(e) {
    console.log(e);
    let index = e.currentTarget.dataset.index;
    this.data.specAndPrice[index].spec = e.detail;
    let specAndPrice = this.data.specAndPrice;
    this.setData({
      specAndPrice
    });
  },

  async getList1() {
    let postData = {
      PageIndex: 1,
      PageRows: 100,
      SortField: "id",
      SortType: "asc"
    };
    const data = await Category.GetDataList(postData);
    data.Data.map(item => {
      item.text = item.Name;
    });
    data.Data.shift();
    // this.data.list1 = data.Data;
    this.setData({
      list1: data.Data
    });
    return data.Data;
  },

  async getList2() {
    let postData = {
      PageIndex: 1,
      PageRows: 100,
      SortField: "id",
      SortType: "asc"
    };
    const data = await Category.Subclassfy(postData);
    this.setData({
      list2: data.Data
    });
    return data.Data;
  },
  getCidByName(name) {
    let id = this.data.list1.find(item => {
      return item.Name == name;
    }).Id;
    return id;
  },
  getCol2ByName(name) {
    let id = this.getCidByName(name);
    let list2 = JSON.parse(JSON.stringify(this.data.list2));
    let data = list2.filter(item => {
      return item.ClassifyId == id;
    });

    this.data.clist2 = data;

    let dataCopy = JSON.parse(JSON.stringify(data));

    let data2 = dataCopy.map(item => {
      item = item.Name;
      return item;
    });
    return data2;
  },
  async getList() {
    const list1 = await this.getList1();
    const list2 = await this.getList2();
    console.log("树形结构",list1)
    let list1Val = [];
    list1.forEach(item => {
      list1Val.push(item.Name);
    });
    // let list2Val = [];
    // list2.forEach(item => {
    //   list2Val.push(item.Name);
    // });
    let val = this.getCol2ByName(list1[0].Name);

    this.setData({
      columns: [
        {
          key: "1",
          values: list1Val,
          className: "column1"
        },
        {
          key: "2",
          values: val,
          className: "column2",
          defaultIndex: 2
        }
      ]
    });
  },

  selectType() {
    this.setData({
      show: true
    });
  },
  onChange(event) {
    const { picker, value, index } = event.detail;
    let val = this.getCol2ByName(value[0]);
    picker.setColumnValues(1, val);
  },
  confirm(e) {
    console.log(e.detail);
    let index = e.detail.index;
    if (index.length == 2) {
      this.setData({
        typeName: e.detail.value.join("/"),
        show: false,
        selectIndex: index
      });
      (this.data.Articlelassify_id = this.data.list1[
        this.data.selectIndex[0]
      ].Id),
        (this.data.Subclassfyid = this.data.clist2[
          this.data.selectIndex[1]
        ].Id);
    }
  },
  cancel() {
    this.setData({
      show: false
    });
  },

  async submit() {
    if (!this.data.title) {
      return Toast("标题不能为空");
    }
    console.log(this.data.specAndPrice);
    let specAndPriceflag = this.data.specAndPrice.some(item => {
      return !item.spec || !item.price || !item.size;
    });

    if (!this.data.id && this.data.selectIndex.length != 2) {
      return Toast("请把分类信息补充完整");
    }
    console.log(specAndPriceflag);
    if(this.data.isShow){
      this.setData({
        specAndPrice:[]
      });
    }
    if ((!this.data.isShow) && specAndPriceflag) {
      return Toast("请将规格/零售价,填写完整");
    }

    let list = [];
    this.data.fileList.forEach(item => {
      list.push(item.url);
    });
    let Imags = list.join(",");

    let postData = {
      Id: this.data.id,
      CreatorId: this.data.id,
      CreateTime: new Date(),
      User_id: this.data.userInfo.Id,
      Title: this.data.title,
      Articlelassify_id: this.data.checked ? 2 :1,
      Content: this.data.content,
      Updatetime: new Date(),
      Imags: Imags,
      PopedomId: this.data.checked
        ? "1290559635618533376"
        : "1290559541989085184",
      PriceaAndMc: this.arrayToString(),
      // Articlelassify_id: this.data.Articlelassify_id,
      Subclassfyid: this.data.Subclassfyid
    };
    console.log("请求的即参数",postData);
    const data = await Article.SaveData(postData);
    console.log(data);
    if (data.Success) {
      Toast("发布成功");
      wx.navigateBack();
    } else {
      Toast(data.Msg);
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {}
});
